local bs = $bs

clear
use "$tempfold/ProdQ_new_klm"

tempfile params
save `params', replace

use "$working/prowess_wits_estimation_qonly_klm.dta", clear

merge m:1 nic_08_2dig using `params'
drop _merge

tabulate nic_08_2dig, sort

***Drop the single product firms that are non-comparable- i.e., missing energy and quantity data
keep if q_s!=. &  energy_intensity!=.

merge m:1 co_code1 year using "$working/first_last_years.dta"
keep if _merge==3
drop _merge

sort product_id year
xtset product_id year
bys co_code1 year: egen nprod = count(co_code1)
tsfill, full
sort product_id year
gen N = missing(L.co_code1)
gen D = missing(f.co_code1)

replace N = . if first_year == 1
replace D = . if last_year == 1

drop if missing(co_code1)

drop cleaned_number_prod
bysort co_code1 year: generate cleaned_number_prods = _N

tabulate cleaned_number_prods

generate omega_j= q_s - beta_l_hat_q * (l + ln_shares) - beta_k_hat_q* ( k + ln_shares) - beta_m_hat_q * (m + ln_shares)  ///
- beta_lk_hat_q*I_sq - beta_km_hat_q*I_sq_km - beta_lm_hat_q*I_sq_lm 
	
egen firm_prod = group(up12 co_code1)
egen firm_year =  group(co_code1 year)

merge 1:m year co_code1 product_name5 using "$tempfold/bssample1"
keep if _merge==3
drop _merge		

ivreghdfe q_s (ln_price = omega_j), absorb(firm_prod firm_year) first cluster(co_code1)

generate sample0 = e(sample)
keep if sample0 == 1

generate sigma_hat= _b[ln_price]	

replace nic_08_2dig = "all"
contract nic_08_2dig sigma_hat 
		
rename _freq Observations
		
save "$tempfold/D_TFPQIV_Qklm", replace

collapse (mean) sigma_hat (sum) Observations

generate bs = `bs'

save "$tempfold/bs_D_TFPQIV_Qklm", replace

clear
use "$BS_fold/bs_D_TFPQIV_Qklm"
append using "$tempfold/bs_D_TFPQIV_Qklm"
save  "$BS_fold/bs_D_TFPQIV_Qklm", replace


